package com.thread.sync.sync02;


/**
 * @author houzheng
 */

/**
 * @author houzheng
 *
 */
public class Synch02 {
    //静态内部类
    static class Main {
        public int i = 10;

        public synchronized void operationSup() {
            try {
                i--;
                System.out.println("Main print int = " + i);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //父类与子类继承使用synchronized修饰也是线程安全的
    static class Sub extends Main {

        public synchronized void operationSub() {
            try {
                while (i > 0) {
                    i--;
                    System.out.println("Sub print i=" + i);
                    Thread.sleep(1000);
                    this.operationSup();//子类中调用父类方法
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //静态内部类可以直接new一个对象,非静态需要new一个外部类实例
                //Synch02.Sub sub=new Synch02.Sub();
                Sub sub = new Sub();
                sub.operationSub();//调用子类方法
            }
        }).start();

    }
}
